﻿var less_width = 0; sum_total = 0; less_sum_title = 0; tab_click_list = [];
var total_list = [];   //记录菜单滚动宽度
var less_total_list = 0; less_one_total = 2;

; !function () {
    $ = layui.$;
    var element = layui.element;

    top.layer.load(1);
    GetObjectInfoFunction_Async("Admin/Handler/BaseHand/MenuHand.ashx", { "act": "GetMenuList" }, function (result) {
        if (result.IsSuccess) {
            window.MenuList = result.data;
            var treeData = ConvertTreeData(result.data, "childMenus");
            $("#navBarId").append(initMenuHtml(treeData));
            element.render();
        }
    })

    //隐藏左侧导航
    //$(".switchMenu").click(function () {
    //    $(".layui-layout-admin").toggleClass("hideMenu");
    //    if ($(this).hasClass("layui-icon-shrink-right")) {
    //        $(".layui-tab-card > .layui-tab-title").css('left', '0');
    //        $(".switchMenu").addClass('layui-icon-spread-left').removeClass('layui-icon-shrink-right');
    //    }
    //    else {
    //        $(".layui-tab-card > .layui-tab-title").css('left', '200px');
    //        $(".switchMenu").addClass('layui-icon-shrink-right').removeClass('layui-icon-spread-left');
    //    }
    //})

    $(document).on("click", ".switchMenu,.admin-nav-mini .layui-side .layui-nav .layui-nav-item", function () {
        var elem = $(".layui-layout-admin");
        var flag = elem.hasClass("admin-nav-mini");
        if (flag) {
            elem.removeClass("admin-nav-mini");
            let tipId = $(this).data("index");
            layui.layer.close(tipId);
        } else {
            elem.addClass("admin-nav-mini");
        }
    })

    //触发事件
    var active = {
        //在这里给active绑定几项事件，后面可通过active调用这些事件
        tabAdd: function (url, id, name) {
            //新增一个Tab项 传入三个参数，分别对应其标题，tab页面的地址，还有一个规定的id，是标签中data-id的属性值
            //关于tabAdd的方法所传入的参数可看layui的开发文档中基础方法部分
            element.tabAdd('menuIframe', {
                title: name,
                content: '<iframe id="' + id + '" data-frameid="' + id + '" scrolling="auto" frameborder="0" src="' + url + '" style="width:100%;height:99%;"></iframe>',
                id: id //规定好的id
            })
            CustomRightClick(id); //给tab绑定右击事件
            FrameWH();  //计算ifram层的大小
            right_fun();
        },
        tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange('menuIframe', id); //根据传入的id传入到指定的tab项
            right_fun();
        },
        tabDelete: function (id) {
            element.tabDelete("menuIframe", id);//删除
            right_fun();
        },
        tabDeleteAll: function (ids) {//删除所有
            $.each(ids, function (i, item) {
                element.tabDelete("menuIframe", item); //ids是一个数组，里面存放了多个id，调用tabDelete方法分别删除
            })
        }
    };


    //监听导航菜单的点击，即左侧菜单栏中内容
    element.on('nav(nav)', function (elem) {
        navTabSwitch(elem);
    });

    var navTabSwitch = function (elem) {
        let menuArr = $.grep(window.MenuList, function (item, idx) {
            return item.MenuCode == elem.attr("data-id");
        });

        var itemMenu = {};
        if (menuArr.length == 0) {
            if (elem.attr("data-id") == null)
                return;
            itemMenu = {
                MenuCode: elem.attr("data-id"),
                MenuName: elem.attr("data-title"),
                Action: "ErrorPage.html"
            };
        }
        else {
            itemMenu = menuArr[0];
        }

        //这时会判断右侧.layui-tab-title属性下的有lay-id属性的li的数目，即已经打开的tab项数目
        if ($(".layui-tab-title li[lay-id]").length <= 0) {
            //如果比零小，则直接打开新的tab项
            active.tabAdd(itemMenu.Action, itemMenu.MenuCode, itemMenu.MenuName);
        } else {
            //否则判断该tab项是否以及存在

            var isData = false; //初始化一个标志，为false说明未打开该tab项 为true则说明已有
            $.each($(".layui-tab-title li[lay-id]"), function () {
                //如果点击左侧菜单栏所传入的id 在右侧tab项中的lay-id属性可以找到，则说明该tab项已经打开
                if ($(this).attr("lay-id") == itemMenu.MenuCode) {
                    isData = true;
                }
            })
            if (isData == false) {
                //标志为false 新增一个tab项
                active.tabAdd(itemMenu.Action, itemMenu.MenuCode, itemMenu.MenuName);
            }
        }
        //最后不管是否新增tab，最后都转到要打开的选项页面上
        active.tabChange(itemMenu.MenuCode);
    }

    window.navTabSwitch = navTabSwitch;

    function CustomRightClick(id) {
        // 获取当前tab对应ul>li
        var li = $(".layui-tab-title li");
        // 获取当前tab对应ul>li的位置
        var ind = 0;
        $.each(li, function (i, item) {
            console.log(item);
            if ($(item).attr('lay-id') == id && i != 0) {
                ind = i;
            }
        });

        //桌面点击右击
        $(".layui-tab-title li:eq(" + ind + ")").on('contextmenu', function (e) {
            var popupmenu = $(".rightmenu");
            popupmenu.find("li").attr('data-id', $(this).attr("lay-id"));

            // 选中当前tab
            $(".layui-tab-title li:eq(" + ind + ")").trigger("click");

            // 菜单浮窗
            //var hideMenu = $(".layui-layout-admin").hasClass("hideMenu");
            //var leftValue = hideMenu ? e.clientX - 200 : e.clientX;
            //var topValue = e.clientY - 40;
            popupmenu.css({ left: e.clientX, top: e.clientY }).show();
            return false;
        });
        //左键点击隐藏
        $('body,iframe,.layui-tab-title li').click(function () {
            $('.rightmenu').hide();
        });
    }

    $(".rightmenu li").click(function () {
        var dataid = $(this).attr("data-id");
        //右键菜单中的选项被点击之后，判断type的类型，决定关闭所有还是关闭当前。
        switch ($(this).attr("data-type")) {
            case "closethis":
                //如果关闭当前，即根据显示右键菜单时所绑定的id，执行tabDelete
                active.tabDelete(dataid)
                break;
            case "closeother":
                //关闭其他页
                {
                    var tabtitle = $(".layui-tab-title li");
                    var ids = new Array();
                    $.each(tabtitle, function (i) {
                        var layid = $(this).attr("lay-id");
                        if (dataid != layid && layid != undefined && layid != "HomeContent")
                            ids[i] = layid;
                    })
                    active.tabDeleteAll(ids);
                }
                break;
            case "closeall":
                //关闭所有页
                {
                    var tabtitle = $(".layui-tab-title li");
                    var ids = new Array();
                    $.each(tabtitle, function (i) {
                        if ($(this).attr("lay-id") != "HomeContent")
                            ids[i] = $(this).attr("lay-id");
                    })
                    //如果关闭所有 ，即将所有的lay-id放进数组，执行tabDeleteAll
                    active.tabDeleteAll(ids);
                }
                break;
            case "refresh":
                // 重新加载iFrame，实现更新。注意：如果你不是使用的iFrame则无效，具体刷新实现自行处理
                var src = $(".layui-tab-item.layui-show").find("iframe").attr("src");
                $(".layui-tab-item.layui-show").find("iframe").attr("src", src);
                //FrameWH();
                break;
            default:
        }
        $('.rightmenu').hide(); //最后再隐藏右键菜单
    })

    FrameWH();
    function FrameWH() {
        var H = $(window).height() - 50 - 41;
        $("iframe").css("height", H + "px");

        //底部固定区域
        //var h = $(window).height() - 40 - 10 - 60 - 50 - 11;
        //$("iframe").css("height", h + "px");
    }

    $(window).resize(function () {
        FrameWH();
    });

    $("#LoginOut").click(function () {
        layer.confirm('确定退出登录吗?', { icon: 3, title: '提示' }, function (index) {
            location.replace("../../Login.aspx");
            layer.close(index);
        });
    });

    //生成树状json格式
    function ConvertTreeData(data, children) {
        var arr = [], hash = {};
        for (i = 0; i < data.length; i++) {
            hash[data[i].MenuId] = data[i];
        }
        for (j = 0; j < data.length; j++) {
            var aVal = data[j], hashVP = hash[aVal.ParentId];
            if (hashVP) {
                !hashVP[children] && (hashVP[children] = []);
                hashVP[children].push(aVal);
            } else {
                arr.push(aVal);
            }
        }
        return arr;
    }

    // 导航菜单的间隔像素
    var menuCell = 10;
    function initMenuHtml(data) {
        var liStr = "";
        // 遍历生成主菜单
        for (var i = 0; i < data.length; i++) {
            let menuIconStr = "", paddName = "";
            if (!StringIsNullOrEmpty(data[i].MenuIcon))
                menuIconStr = "<i class=\"layui-icon " + data[i].MenuIcon + "\"></i>";
            else
                paddName = "style=\"padding-left: 16px;\"";
            // 判断是否存在子菜单
            if (data[i].childMenus != null && data[i].childMenus.length > 0) {
                liStr += "<li class=\"layui-nav-item\"><a class=\"\" data-tips=\"" + data[i].MenuName + "\" href=\"javascript:;\">" + menuIconStr + "&emsp;<cite " + paddName + ">" + data[i].MenuName + "</cite></a>\n" +
                    "<dl class=\"layui-nav-child\">\n";
                // 遍历获取子菜单
                for (var k = 0; k < data[i].childMenus.length; k++) {
                    liStr += getChildMenu(data[i].childMenus[k], 0);
                }
                liStr += "</dl></li > ";
            } else {
                liStr += "<li class=\"layui-nav-item\"><a class=\"\" data-tips=\"" + data[i].MenuName + "\" href=\"javascript:;\">" + menuIconStr + "&emsp;<cite " + paddName + ">" + data[i].MenuName + "</cite></a></li>";
            }
        };

        //return "<ul class=\"layui-nav layui-nav-tree\"  lay-filter=\"nav\">\n" + liStr + "</ul>";
        return liStr;
    }

    // 递归生成子菜单
    function getChildMenu(subMenu, num) {
        let subStr = "";

        let menuIconStr = "", paddName = "";
        if (!StringIsNullOrEmpty(subMenu.MenuIcon))
            menuIconStr = "<i class=\"layui-icon " + subMenu.MenuIcon + "\"></i>";
        else
            paddName = "style=\"padding-left: 16px;\"";
        if (subMenu.childMenus != null && subMenu.childMenus.length > 0) {
            subStr += "<dd><dl><dd class=\"\" ><a style=\"padding-Left:" + (num * menuCell + 28) + "px\" class=\"\" href=\"javascript:;\">" + menuIconStr + "&emsp;<cite " + paddName + ">" + subMenu.MenuName + "</cite></a>" +
                "<dl class=\"layui-nav-child\">\n";
            for (let j = 0; j < subMenu.childMenus.length; j++) {
                if (j == 0)
                    num++;//同级左内边距一样
                subStr += getChildMenu(subMenu.childMenus[j], num);
            }
            subStr += "</dl></dd></dl></dd>";
        } else {
            subStr += "<dd><a class=\"\" style=\"padding-Left:" + (num * menuCell + 28) + "px\" href=\"javascript:;\" data-id=\"" + subMenu.MenuCode + "\" data-title=\"" + subMenu.MenuName + "\" >" + menuIconStr + "&emsp;<cite " + paddName + ">" + subMenu.MenuName + "</cite></a></dd>";
        }
        return subStr;
    }

    /* 最大化窗口 */
    $(".timo-screen-full").on("click", function (e) {
        e.preventDefault();
        if (!$(this).hasClass("full-on")) {
            var docElm = document.documentElement;
            var full = docElm.requestFullScreen || docElm.webkitRequestFullScreen ||
                docElm.mozRequestFullScreen || docElm.msRequestFullscreen;
            "undefined" !== typeof full && full && full.call(docElm);
        } else {
            document.exitFullscreen ? document.exitFullscreen()
                : document.mozCancelFullScreen ? document.mozCancelFullScreen()
                    : document.webkitCancelFullScreen ? document.webkitCancelFullScreen()
                        : document.msExitFullscreen && document.msExitFullscreen()
        }
        $(this).toggleClass("full-on");
    });

    //向右移动
    $('#rightPage').click(function () {
        var sum_title = parseFloat($('.layui-tab-title').width());
        //temp_data存上一次宽度
        var temp_width = 0; temp_data = 0; one_total_list = 0;
        var temp_total = $('.layui-tab-title li[lay-id]').length;
        for (var i = sum_total; i < temp_total; i++) {
            tab_click_list.push($('.layui-tab-title li').eq(i).attr("lay-id"));
            temp_width = parseFloat($('.layui-tab-title li').eq(i).width()) + 30;
            if (less_width > sum_title + less_sum_title) {
                less_width = less_width - temp_data;
                less_sum_title = less_width;
                break;
            } else {
                //console.log('ok');
                less_width += temp_width;
                temp_data = temp_width;
                sum_total = i;
            }
        }

        if (sum_total < temp_total - 1) {
            //用列表记录菜单滚动所有宽度
            total_list.push(-less_width);
            console.log(total_list, '个数');
            var css = {
                "left": -less_width,
            };
            $('.layui-tab-title').css(css);
        }

    });


    //向左移动
    $('#leftPage').click(function () {
        less_total_list = total_list.length - less_one_total;
        ceshi = -total_list[less_total_list];
        if (less_total_list >= 0) {
            console.log(less_total_list, "less_total_list");
            var css = {
                "left": total_list[less_total_list]
            };
            $('.layui-tab-title').css(css);
            less_one_total += 1;
        } else if (less_total_list < 0) {
            var css = {
                "left": 0
            };
            $('.layui-tab-title').css(css);
            //清除所有已赋值的变量
            less_width = 0; sum_total = 0; less_sum_title = 0; total_list = [];
        }
    });

    //移动函数
    function right_fun() {
        less_width = 0; sum_total = 0; less_sum_title = 0;
        var total_list = [];   //记录菜单滚动宽度
        var sum_title = parseFloat($('.layui-tab-title').width());
        //temp_data存上一次宽度
        var temp_width = 0; temp_data = 0; one_total_list = 0;
        var temp_total = $('.layui-tab-title li[lay-id]').length;
        for (var i = sum_total; i < temp_total; i++) {
            console.log($('.layui-tab-title li').eq(i).attr("lay-id"), "lay-id");
            temp_width = parseFloat($('.layui-tab-title li').eq(i).width()) + 30;
            if (less_width > sum_title + less_sum_title) {
                less_width = less_width - temp_data;
                less_sum_title = less_width;
                break;
            } else {
                //console.log('ok');
                less_width += temp_width;
                temp_data = temp_width;
                sum_total = i;
            }
        }

        if (sum_total < temp_total - 1) {
            //用列表记录菜单滚动所有宽度
            total_list.push(-less_width);
            console.log(total_list, '个数');
            var css = {
                "left": -less_width,
            };
            $('.layui-tab-title').css(css);
        }

    }

    $(document).on("mouseenter mouseleave", ".admin-nav-mini .layui-side .layui-nav .layui-nav-item", function (event) {
        if (event.type == "mouseenter") {
            let tipTxt = $(this).find("a").attr("data-tips");
            if (!StringIsNullOrEmpty(tipTxt)) {
                let tipId = layui.layer.tips(tipTxt, this);
                $(this).data("index", tipId);
            }
        } else if (event.type == "mouseleave") {
            let tipId = $(this).data("index");
            layui.layer.close(tipId);
        }
    })

}();